// controllers/goodsController.js
const { Goods, GoodsSku, User, Customer } = require("../models");

// 创建商品（绑定当前登录用户ID）
async function createGoods(ctx) {
  console.log(ctx);

  const userId = ctx.state.user.id;
  const data = ctx.request.body;

  data.user_id = userId;

  const goods = await Goods.create(data, { include: ["goods_skus"] });
  ctx.body = { code: 0, msg: "创建成功", data: goods };
}

// 查询当前用户商品列表
async function getGoodsList(ctx) {
  const userId = ctx.state.user.id;

  // 分页参数（可选）
  const { page = 1, limit = 20 } = ctx.query;
  const offset = (page - 1) * limit;

  const { count, rows } = await Goods.findAndCountAll({
    where: { user_id: userId },
    include: [
      { model: GoodsSku, as: "goods_skus" },
      { model: User, as: "owner", attributes: ["id", "username", "nickname"] },
    ],
    limit: +limit,
    offset,
    order: [["createdAt", "DESC"]],
  });

  ctx.body = { code: 0, data: { total: count, list: rows } };
}

// 查询单个商品（当前用户所有或其绑定客户可访问）
async function getGoodsById(ctx) {
  const userId = ctx.state.user.id;
  const goodsId = ctx.params.id;

  // 查商品所属用户ID
  const goods = await Goods.findByPk(goodsId, {
    include: [{ model: GoodsSku, as: "goods_skus" }],
  });

  if (!goods) {
    ctx.throw(404, "商品不存在");
  }

  if (goods.user_id !== userId) {
    // 不是创建者，检查是否是绑定客户（客户表里有用户ID和客户ID的关联）
    const customer = await Customer.findOne({
      where: { user_id: goods.user_id, id: userId },
    });
    if (!customer) {
      ctx.throw(403, "无权限访问该商品");
    }
  }

  ctx.body = { code: 0, data: goods };
}

// 更新商品（只能创建者）
async function updateGoods(ctx) {
  const userId = ctx.state.user.id;
  const goodsId = ctx.params.id;
  const data = ctx.request.body;

  const goods = await Goods.findByPk(goodsId);
  if (!goods) {
    ctx.throw(404, "商品不存在");
  }
  if (goods.user_id !== userId) {
    ctx.throw(403, "无权限修改该商品");
  }

  await goods.update(data);
  ctx.body = { code: 0, msg: "更新成功", data: goods };
}

// 删除商品（只能创建者）
async function deleteGoods(ctx) {
  const userId = ctx.state.user.id;
  const goodsId = ctx.params.id;

  const goods = await Goods.findByPk(goodsId);
  if (!goods) {
    ctx.throw(404, "商品不存在");
  }
  if (goods.user_id !== userId) {
    ctx.throw(403, "无权限删除该商品");
  }

  await goods.destroy();
  ctx.body = { code: 0, msg: "删除成功" };
}

module.exports = {
  createGoods,
  getGoodsList,
  getGoodsById,
  updateGoods,
  deleteGoods,
};
